package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.woyao.core.PayResult;
import com.woyao.core.model.Balance;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.GetBalanceResponse;
import com.woyao.core.model.Service;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.DateUtil;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.Map;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class MoneyActivity extends AppCompatActivity {
    private LinearLayout alllist = null;
    private TextView balanceAmountTxt = null;
    private TextView discountTxt = null;
    private TextView payAmountTxt = null;
    private Button payButton = null;
    private  Button claimBtn = null;
    ProgressDialog progressDialog;
    private GetBalanceResponse balance;
    private static final int SDK_PAY_FLAG = 1;

    private ServiceMgmtAdapter serviceAdapter;
    private RecyclerView serviceList = null;
    LinearLayoutManager serviceLayoutManager = null;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult result = new PayResult((Map<String, String>) msg.obj);

            String resultStatus = result.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(MoneyActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                payAmountTxt.setText("");
                loadData();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(MoneyActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
            }


        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


        serviceList = (RecyclerView)findViewById(R.id.id_service_items);
        serviceLayoutManager = new LinearLayoutManager(this);
        serviceLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        serviceList.setLayoutManager(serviceLayoutManager);
        serviceList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        alllist = (LinearLayout)findViewById(R.id.balance_list);
        balanceAmountTxt = (TextView) findViewById(R.id.balance_amount);
        discountTxt = (TextView) findViewById(R.id.balance_condition);
        payAmountTxt = (EditText) findViewById(R.id.pay_amount);
        payButton = (Button) findViewById(R.id.alipay);

        TextView memberProtocol = (TextView) findViewById(R.id.id_member_protocol);

        memberProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MoneyActivity.this, WebviewActivity.class);
                intent.putExtra("title", "会员服务协议");
                intent.putExtra("link", "https://www.woyaooo.com/member.html");
                startActivity(intent);
            }
        });

        claimBtn = (Button) findViewById(R.id.withdraw);

        claimBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final EditText inputServer = new EditText(MoneyActivity.this);
                Dialog alertDialog = new AlertDialog.Builder(MoneyActivity.this).
                        setTitle("提现").
                        setMessage("平台须收取1/3的服务费，请输入支付宝账户").
                        setIcon(R.drawable.ic_launcher).
                        setView(inputServer).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                withdraw( inputServer.getText().toString());
                            }
                        }).
                        create();
                alertDialog.show();
            }
        });

        payButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Float amount =  Float.parseFloat(payAmountTxt.getText().toString() ) ;
                if (amount < balance.getBasic() ){
                    Dialog alertDialog = new AlertDialog.Builder(MoneyActivity.this).
                            setTitle("提示").
                            setMessage("最低起充量是" + balance.getBasic() + "元").
                            setIcon(R.drawable.ic_launcher).
                            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    payAmountTxt.requestFocus();
                                }
                            }).
                            create();
                    alertDialog.show();
                    return;
                }

                appPay("1",payAmountTxt.getText().toString());
            }
        });

        Intent intent = getIntent();

        Double money = intent.getDoubleExtra("money", 0.0);
        if ( money >0 ) {
            payAmountTxt.setText(money + "");
        }else{
            payAmountTxt.setText("");
        }

        loadData();


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }



    private void withdraw( final String account ){

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在启动支付······");
        progressDialog.show();

        final String payamount = payAmountTxt.getText().toString();
        AsyncTask<Void,Void,BaseResponse> task =new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.withdraw(userId,payamount , "alipay","android" );
                try {
                    BaseResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final BaseResponse response) {
                progressDialog.dismiss();
//

                Dialog alertDialog = new AlertDialog.Builder(MoneyActivity.this).
                        setTitle("信息").
                        setMessage(response.getMessage() ).
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (response.isSuccess()) {
                                    loadData();
                                }
                            }
                        }).
                        create();
                alertDialog.show();


            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }



    private void appPay(final String servie_id ,final String pay_amount){

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在启动支付······");
        progressDialog.show();



        AsyncTask<Void,Void,BaseResponse> task =new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.getOrder(userId,pay_amount, servie_id );
                try {
                    BaseResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final BaseResponse response) {
                progressDialog.dismiss();
                if (response.isSuccess()){
                    pay(response.getMessage());
                }
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }

    private void pay(final String orderInfo ){

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(MoneyActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo,true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private AsyncTask<Void,Void,GetBalanceResponse> task = null;
    private void loadData(){
        if(task != null)return;

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        task =new AsyncTask<Void, Void, GetBalanceResponse>() {
            @Override
            protected GetBalanceResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetBalanceResponse> responseCall = svc.getBalance(userId);
                try {
                    GetBalanceResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetBalanceResponse response) {
                progressDialog.dismiss();
                render(response);
                task = null;
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }
    private void render(GetBalanceResponse response){
        if (response.isSuccess() == false ){
            return;
        }

        balance = response ;
//        balanceAmountTxt.setText( "账户余额: "+ response.getMessage()+" 元");
        balanceAmountTxt.setText(  response.getMessage());
        discountTxt.setText( response.getCondition());


        serviceAdapter = new ServiceMgmtAdapter(this,  response.getServices() );
        serviceAdapter.setChangedHandler(new ServiceMgmtAdapter.Changed() {
            @Override
            public void view(Service ms) {
                if (!ms.getLink().equals("")){
                    Intent intent = new Intent();
                    intent.setClass(MoneyActivity.this, WebviewActivity.class);
                    intent.putExtra("title", "服务详情");
                    intent.putExtra("link", ms.getLink());
                    startActivity(intent);
                }

            }

            @Override
            public void buy(Service ms) {
                appPay(ms.getService_id(),ms.getAmount() +"");
            }
        });


        serviceList.setAdapter(serviceAdapter);

        alllist.removeAllViews();
        LinearLayout item = (LinearLayout) LayoutInflater.from(MoneyActivity.this).inflate(R.layout.balance_item, null);

        TextView theid = (TextView)item.findViewById(R.id.balance_id);
        TextView thetype = (TextView)item.findViewById(R.id.balance_type);
        TextView theamount = (TextView)item.findViewById(R.id.balance_amount);
        TextView thestatus = (TextView)item.findViewById(R.id.balance_status);
        TextView thememo = (TextView)item.findViewById(R.id.balance_memo);
        TextView create_time = (TextView)item.findViewById(R.id.balance_created);

        theid.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        theid.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        thetype.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        thetype.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        theamount.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        theamount.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        thestatus.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        thestatus.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        thememo.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        thememo.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        create_time.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        create_time.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        alllist.addView(item);


            for(Balance bal : response.getContent()){
                item = (LinearLayout) LayoutInflater.from(MoneyActivity.this).inflate(R.layout.balance_item, null);

                 theid = (TextView)item.findViewById(R.id.balance_id);
                 thetype = (TextView)item.findViewById(R.id.balance_type);
                 theamount = (TextView)item.findViewById(R.id.balance_amount);
                 thestatus = (TextView)item.findViewById(R.id.balance_status);
                thememo = (TextView)item.findViewById(R.id.balance_memo);
                 create_time = (TextView)item.findViewById(R.id.balance_created);

                theid.setText( bal.getId() +""  );
                thetype.setText(bal.getType());
                theamount.setText(bal.getAmount()+"");
                thestatus.setText(bal.getStatus());
                thememo.setText(bal.getMemo());
                create_time.setText( DateUtil.format(bal.getCreated()));

                alllist.addView(item);
            }


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
